package com.zjeav.lingjiao.ui.book;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.dalimao.corelibrary.view.SelfDialog;
import com.google.gson.JsonSyntaxException;
import com.maning.mndialoglibrary.MProgressDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.BuyRecordAdapter;
import com.zjeav.lingjiao.base.adapter.MyExpandableListView;
import com.zjeav.lingjiao.base.baseBean.BaseActivity;
import com.zjeav.lingjiao.base.baseBean.BaseApplication;
import com.zjeav.lingjiao.base.baseBean.BookList;
import com.zjeav.lingjiao.base.baseBean.Group;
import com.zjeav.lingjiao.base.baseBean.ItemResource;
import com.zjeav.lingjiao.base.baseBean.PayResult;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.baseBean.UserBuyReCord;
import com.zjeav.lingjiao.base.comon.CommonPersenter;
import com.zjeav.lingjiao.base.comon.CommonView;
import com.zjeav.lingjiao.base.config.BaseConfig;
import com.zjeav.lingjiao.base.request.BookRequest;
import com.zjeav.lingjiao.base.request.FreePay;
import com.zjeav.lingjiao.base.request.OrderSubscribeRequest;
import com.zjeav.lingjiao.base.response.AccessToken;
import com.zjeav.lingjiao.base.response.BookDetailResponse;
import com.zjeav.lingjiao.base.response.OrderSubcribeResponse;
import com.zjeav.lingjiao.base.tools.FileUtils;
import com.zjeav.lingjiao.base.tools.LocalUtils;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.tools.SystemTools;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.base.utils.NetworkUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.home.persenter.MainPersenter;
import com.zjeav.lingjiao.ui.music.MusicActivity;
import com.zjeav.lingjiao.ui.music.MusicService;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;
import com.zjeav.lingjiao.ui.presenter.ShopPresenter;

import org.xutils.DbManager;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;

import static com.zjeav.lingjiao.base.tools.SystemTools.isServiceRunning;

/**
 * 课本详情
 */
public class BookDetialActivity extends BaseActivity implements BookDetailContract.View, View.OnClickListener,
        CommonView.View, BookDetailContract.ShopView, BookDetailContract.BookCollectView, MyExpandableListView.ClickListener {

    private int loadCount = 0;
    private ImageView book_img;
    private TextView book_txt, action_txt, type_1, type_2, type_3;
    private WebView book_intro_txt;
    private RecyclerView buy_history_rw;
    private RefreshLayout refreshLayout;
    private RecyclerView mRecyclerView;

    private ResponseBody downBody, downBody2;
    private BuyRecordAdapter buyRecordAdapter; //购买适配器

    private static final int SDK_PAY_FLAG = 1;
    private static MainPersenter persenter;
    private CommonPersenter commonPersenter;
    private BookDetailResponse bookDetailResponse;
    private static int id;
    private static int index = 1;
    private static int size = 10;

    private String metaName, lrcName;
    private ArrayList<UserBuyReCord> data = new ArrayList<>();
    private IWXAPI api;
    private ShopPresenter shopPresenter;
    private ItemResource resource;
    private View view;
    private DbManager db;
    private int action_type = 0;//0 支付，1：收藏 2取消收藏 3.免费订阅
    private BookPresenter bookPresenter;
    private PopupWindow popupWindow;
    private View contentView;
    private RelativeLayout dialog_zhifubao, dialog_wechat;//;
    private ImageView recharge_zhifubao_cb, recharge_wechat_cb, recharge_dialog_close;
    private TextView dialog_confirm_pay, pay_price;
    private int PayType = 0;//2:weixin 1:zhifubao
    private SelfDialog selfDialog;
    private boolean mallmode;

    private ExpandableListView expandableListView;
    private MyExpandableListView myExpandableListView;// 二级列表适配器

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.book_detail_layout);
        id = getIntent().getIntExtra("id", 0);
        persenter = new MainPersenter(this);
        commonPersenter = new CommonPersenter(this);
        mallmode = (boolean) SharedPreferencesUtils.getParam(this, "mallmode", false);
        init();
    }

    private void init() {
        db = BaseApplication.dbManager;
        api = WXAPIFactory.createWXAPI(this, BaseConfig.APP_ID);
        shopPresenter = new ShopPresenter(this);
        bookPresenter = new BookPresenter(this);
        book_img = findViewById(R.id.book_img);
        book_txt = findViewById(R.id.book_txt);
        mRecyclerView = findViewById(R.id.recycle_view);
        book_intro_txt = findViewById(R.id.book_intro_txt);

        expandableListView = findViewById(R.id.expandableListView);
        expandableListView.setGroupIndicator(null);

        WebSettings webSettings = book_intro_txt.getSettings();
        webSettings.setDatabaseEnabled(true);
        // 缓存白屏
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath() + "/webcache";
        webSettings.setAppCachePath(appCachePath);
        book_intro_txt.setWebViewClient(new MyWebViewClient());
        action_txt = findViewById(R.id.action_txt);
        action_txt.setOnClickListener(this);
        type_1 = findViewById(R.id.type_1);
        type_2 = findViewById(R.id.type_2);
        type_3 = findViewById(R.id.type_3);
        type_1.setOnClickListener(this);
        type_2.setOnClickListener(this);
        type_3.setOnClickListener(this);
        type_1.setTextColor(ContextCompat.getColor(this, R.color.white));
        type_3.setTextColor(ContextCompat.getColor(this, R.color.black));
        type_2.setTextColor(ContextCompat.getColor(this, R.color.black));
        type_1.setBackground(ContextCompat.getDrawable(this, R.drawable.border_bg_blue));
        type_2.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
        type_3.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
        refreshLayout = findViewById(R.id.refreshLayout);
        buy_history_rw = findViewById(R.id.buy_history_rw);
        this.book_intro_txt.setVisibility(View.GONE);
        this.buy_history_rw.setVisibility(View.GONE);

        buyRecordAdapter = new BuyRecordAdapter(this);
        buy_history_rw.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
        buy_history_rw.setLayoutManager(new LinearLayoutManager(this));
        buy_history_rw.setAdapter(buyRecordAdapter);
        showPopwindow();
        if (mallmode) {
            action_txt.setVisibility(View.VISIBLE);
        } else {
            action_txt.setVisibility(View.GONE);
        }


        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                index++;
                persenter.getBuyHistory(id, new BookRequest(index, size));
                refreshlayout.finishLoadmoreWithNoMoreData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            index = 1;
                            data.clear();
                            persenter.getBuyHistory(id, new BookRequest(index, size));
                            refreshLayout.finishRefresh();
                        } catch (JsonSyntaxException e) {
                            UIUtils.showToast("数据加载异常");
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        popupWindow.dismiss();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, "支付失败: " + payResult);
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        persenter.getBookDetail(id);
        BookRequest request = new BookRequest(index, size);
        persenter.getBuyHistory(id, request);

    }

    private void showDiagle() {
        selfDialog = new SelfDialog(this);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("当前网络不是WIFI状态，是否继续下载?");
        selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                selfDialog.dismiss();
                MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);

            }
        });
        selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                selfDialog.dismiss();
            }
        });
        selfDialog.show();
    }


    private void imgReset(WebView webView) {
        webView.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName('img'); "
                + "for(var i=0;i<objs.length;i++)  " + "{"
                + "var img = objs[i];   "
                + "    img.style.width = '100%';   "
                + "    img.style.height = 'auto';   "
                + "}" + "})()");
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //  html加载完成之后，调用js的方法
            imgReset(view);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            view.loadUrl(url);
            if (url.startsWith("http://") || url.startsWith("https://")) {
                view.loadUrl(url);
                view.stopLoading();
                return true;
            }
            return false;
        }
    }

    @Override
    public void ShowBookDetail(BookDetailResponse response) {
        bookDetailResponse = response;
        if (bookDetailResponse.getPrice() != 0) {
            action_type = 0;
            action_txt.setText("立即订阅");
        } else {
            action_type = 3;
            action_txt.setText("免费订阅");
        }

        if (bookDetailResponse.isSubscribed()) {
            action_txt.setText("已订阅");
        } else {
            action_txt.setText("立即订阅");
        }

        Glide.with(getApplication()).load(response.getCover())
                .into(this.book_img);
        String text = String.format(getResources().getString(R.string.book_info), response.getTitle(), response.getPress(), response.getIsbn(), response.getPrice() + "");
        this.book_txt.setText(text);

        List<String> stritemtitle = new ArrayList<>();
        List<String> jsongroup = new ArrayList<>();


        for (int i = 0; i < response.getGroups().size(); i++) {
            Group group = response.getGroups().get(i);

            stritemtitle.add(group.getGroupName());
            String strgroupInfo = JSONArray.toJSONString(group.getGroups());
            jsongroup.add(strgroupInfo);
        }


        int sizegroup =stritemtitle.size();
        String[] strings=new String[sizegroup];
        String[][] childst= new String[sizegroup][];

        try {
            int position;
            for(int j=0;j<stritemtitle.size();j++){

                position = j;
                strings[position]=stritemtitle.get(position);

                String gameListStr = jsongroup.get(position);
                List<ItemResource> newData = JSON.parseArray(gameListStr, ItemResource.class);
                childst[j]=new String[newData.size()];
                for (int m = 0;m<newData.size();m++){

                    ItemResource itemResource = newData.get(m);
                    String str = JSON.toJSONString(itemResource);
                    childst[position][m] =  str;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        myExpandableListView = new MyExpandableListView(this,strings,childst,id,db,this);
        myExpandableListView.isPayed(bookDetailResponse.isSubscribed());
        expandableListView.setAdapter(myExpandableListView);

        this.book_intro_txt.loadData("<html><body>" + response.getIntro().replace("\\r", "") + "</body></html>",
                "text/html; charset=UTF-8", null);
    }

    @Override
    public void showBuyHistory(ArrayList<UserBuyReCord> list) {
        this.data.addAll(list);
        buyRecordAdapter.replaceData(data);
    }

    @Override
    public void ShowFail(Throwable throwable) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
        loadProgressDialog.cancel();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.type_1:
                this.book_intro_txt.setVisibility(View.GONE);
                this.expandableListView.setVisibility(View.VISIBLE);
                this.buy_history_rw.setVisibility(View.GONE);
                type_1.setTextColor(ContextCompat.getColor(this, R.color.white));
                type_3.setTextColor(ContextCompat.getColor(this, R.color.black));
                type_2.setTextColor(ContextCompat.getColor(this, R.color.black));
                type_1.setBackground(ContextCompat.getDrawable(this, R.drawable.border_bg_blue));
                type_2.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                type_3.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                break;
            case R.id.type_2:
                type_2.setTextColor(ContextCompat.getColor(this, R.color.white));
                type_1.setTextColor(ContextCompat.getColor(this, R.color.black));
                type_3.setTextColor(ContextCompat.getColor(this, R.color.black));
                this.book_intro_txt.setVisibility(View.VISIBLE);
                this.expandableListView.setVisibility(View.GONE);
                this.buy_history_rw.setVisibility(View.GONE);
                type_2.setBackground(ContextCompat.getDrawable(this, R.drawable.border_bg_blue));
                type_1.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                type_3.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                break;
            case R.id.type_3:
                this.book_intro_txt.setVisibility(View.GONE);
                this.expandableListView.setVisibility(View.GONE);
                this.buy_history_rw.setVisibility(View.VISIBLE);
                type_3.setTextColor(ContextCompat.getColor(this, R.color.white));
                type_1.setTextColor(ContextCompat.getColor(this, R.color.black));
                type_2.setTextColor(ContextCompat.getColor(this, R.color.black));
                type_3.setBackground(ContextCompat.getDrawable(this, R.drawable.border_bg_blue));
                type_1.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                type_2.setBackground(ContextCompat.getDrawable(this, R.drawable.shap_radiusgwhite));
                break;
            case R.id.action_txt:
                if (action_type == 0) {
                    //从底部显示
                    pay_price.setText("￥: " + bookDetailResponse.getPrice());
                    popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
                } else if (action_type == 1) {
                    MProgressDialog.showProgress(this, "收藏...");
                    bookPresenter.collectBook(bookDetailResponse.getId());
                } else if (action_type == 2) {
                    MProgressDialog.showProgress(this, "取消收藏...");
                    bookPresenter.removeCollectBook(bookDetailResponse.getId());
                } else if (action_type == 3) {
                    MProgressDialog.showProgress(this, "免费订阅");
                    bookPresenter.freePay(new FreePay(bookDetailResponse.getId(), SystemTools.getSystemModel(), SystemTools.getUniqueId(this)));
                }

                break;
            case R.id.dialog_wechat:
                PayType = 2;
                recharge_wechat_cb.setBackground(getResources().getDrawable(R.mipmap.choos_sel));
                recharge_zhifubao_cb.setBackground(getResources().getDrawable(R.mipmap.choos_normal));
                break;
            case R.id.dialog_zhifubao:
                PayType = 1;
                recharge_zhifubao_cb.setBackground(getResources().getDrawable(R.mipmap.choos_sel));
                recharge_wechat_cb.setBackground(getResources().getDrawable(R.mipmap.choos_normal));
                break;
            case R.id.dialog_confirm_pay:
                String type;
                if (PayType == 0) {
                    UIUtils.showToast("您尚未选择支付方式");
                    return;
                }
                if (PayType == 1) {
                    type = "支付宝";
                } else {
                    type = "微信";
                }
                ArrayList<BookList> books = new ArrayList();
                books.add(new BookList(bookDetailResponse.getId(), 1, bookDetailResponse.getPrice()));
                OrderSubscribeRequest request = new OrderSubscribeRequest(type, "", books);
                shopPresenter.getOder(request);
                action_txt.setEnabled(false);
                Toast.makeText(this, "获取订单中...", Toast.LENGTH_SHORT).show();
                action_txt.setEnabled(true);
                break;
            case R.id.recharge_dialog_close:
                popupWindow.dismiss();
                break;
        }
    }

    private MyHandler myHandler = new MyHandler(this);

    @Override
    public void ShowShop(final OrderSubcribeResponse response) {
        popupWindow.dismiss();
        if (PayType == 1) {

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(BookDetialActivity.this);
                    Map<String, String> result = alipay.payV2(response.getBusinessinfo().getOrderString(), true);

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {
            api.registerApp(BaseConfig.APP_ID);
            Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
            PayReq req = new PayReq();
            Log.d("order", JSON.toJSONString(response) + "");
            if (response.getBusinessinfo() != null) {
                req.appId = response.getBusinessinfo().getAppid();
                req.partnerId = response.getBusinessinfo().getPartnerId();
                req.prepayId = response.getBusinessinfo().getPrepayId();
                req.nonceStr = response.getBusinessinfo().getNonceStr();
                req.timeStamp = response.getBusinessinfo().getTimeStamp();
                req.sign = response.getBusinessinfo().getSign();
            }
            req.packageValue = "Sign=WXPay";
            req.extData = "app data";// optional
            api.sendReq(req);
        }
    }

    @Override
    public void BookCollectSuccess(Result result) {
        MProgressDialog.dismissProgress();
        action_txt.setText("取消收藏");
        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();

    }

    /**
     * 显示popupWindow
     */
    private void showPopwindow() {
        //加载弹出框的布局
        contentView = LayoutInflater.from(BookDetialActivity.this).inflate(
                R.layout.dialog_pay, null);
        dialog_zhifubao = contentView.findViewById(R.id.dialog_zhifubao);
        pay_price = contentView.findViewById(R.id.pay_price);
        dialog_zhifubao.setOnClickListener(this);
        recharge_zhifubao_cb = contentView.findViewById(R.id.recharge_zhifubao_cb);
        recharge_dialog_close = contentView.findViewById(R.id.recharge_dialog_close);
        recharge_dialog_close.setOnClickListener(this);
        dialog_wechat = contentView.findViewById(R.id.dialog_wechat);
        recharge_wechat_cb = contentView.findViewById(R.id.recharge_wechat_cb);
        dialog_wechat.setOnClickListener(this);
        dialog_confirm_pay = contentView.findViewById(R.id.dialog_confirm_pay);
        dialog_confirm_pay.setOnClickListener(this);
        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
        popupWindow.setAnimationStyle(R.style.recharge_pay_dialog);

    }

    @Override
    public void RemoveBookCollect(Result result) {
        MProgressDialog.dismissProgress();
        action_txt.setText("收藏");
        Toast.makeText(this, "取消收藏成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void FreePay(Result result) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, "免费订阅成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void ShowError(Throwable throwable, String message) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, ErrorUtils.showError(throwable, message), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void ItemClick(ItemResource itemResource, int type, int position, View view) {
        this.view = view;
        if (type == 0) {
            resource = itemResource;
            metaName = resource.getTitle() + ".mp3";
            lrcName = resource.getTitle() + ".lrc";
            boolean is4G = (boolean) SharedPreferencesUtils.getParam(BookDetialActivity.this, "is4G", false);
            int netType = NetworkUtils.getNetWorkType(BookDetialActivity.this);
            MusicActivity.mp3Infos = LocalUtils.getList(db, bookDetailResponse.getId());
            boolean isLoad = false;
            if (MusicActivity.mp3Infos != null) {
                for (int i = 0; i < MusicActivity.mp3Infos.size(); i++) {
                    if (resource.getId() == MusicActivity.mp3Infos.get(i).getId()) {
                        isLoad = true;
                        if (FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getUrl()) && FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getSrturl())) {
                            if (isServiceRunning(getBaseContext(), "com.zjeav.lingjiao.ui.music.MusicService")) {
                                stopService(new Intent(BookDetialActivity.this, MusicService.class));
                            }
                            Intent musicintent = new Intent(BookDetialActivity.this, MusicActivity.class);
                            //当前播放的位置
                            musicintent.putExtra("position", String.valueOf(i));
                            musicintent.putExtra("type", 1);
                            //启动音乐播放界面
                            startActivity(musicintent);
                        } else {
                            LocalUtils.deleItem(db, resource.getId());
                            if (netType != 1) {
                                if (!is4G) {
                                    showDiagle();
                                } else {
                                    MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                                    commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                                    commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                                }

                            } else {
                                MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                                commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                                commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                            }
                        }
                    }
                }
            }

            if (!isLoad) {
                if (netType != 1) {
                    if (!is4G) {
                        showDiagle();
                    } else {
                        MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                        commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                        commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                    }

                } else {
                    MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                    commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                    commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                }
            }

        } else if (type == 1) {
            resource = itemResource;
            MusicActivity.mp3Infos = LocalUtils.getList(db, bookDetailResponse.getId());

            if (MusicActivity.mp3Infos != null) {
                for (int i = 0; i < MusicActivity.mp3Infos.size(); i++) {
                    if (MusicActivity.mp3Infos.get(i).getId() == resource.getId()) {
                        if (FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getUrl()) && FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getSrturl())) {
                            if (isServiceRunning(getBaseContext(), "com.zjeav.lingjiao.ui.music.MusicService")) {
                                stopService(new Intent(BookDetialActivity.this, MusicService.class));
                            } else {
                                SharedPreferencesUtils.setParam(this, "currentTime", 0);
                            }
                            int currentTime = (int) SharedPreferencesUtils.getParam(getApplicationContext(), "currentTime", 0);
                            Intent musicintent = new Intent(BookDetialActivity.this, MusicActivity.class);
                            //当前播放的位置
                            musicintent.putExtra("position", String.valueOf(i));
                            musicintent.putExtra("currentTime", currentTime);
                            musicintent.putExtra("type", 1);
                            //启动音乐播放界面
                            startActivity(musicintent);
                        } else {
                            LocalUtils.deleItem(db, resource.getId());
                            boolean is4G = (boolean) SharedPreferencesUtils.getParam(BookDetialActivity.this, "is4G", false);
                            int netType = NetworkUtils.getNetWorkType(BookDetialActivity.this);

                            if (netType != 1) {
                                if (!is4G) {
                                    showDiagle();
                                } else {
                                    MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                                    commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                                    commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                                }

                            } else {
                                MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                                commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                                commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
                            }

                        }
                    }

                }
            } else {
                MProgressDialog.showProgress(BookDetialActivity.this, "下载中...");
                commonPersenter.downLoad(resource.getMetadata().getUrl(), 1);
                commonPersenter.downLoad(resource.getMetadata().getSrturl(), 2);
            }
        } else {
            Toast.makeText(this, "请先订阅，暂不能播放", Toast.LENGTH_SHORT).show();
        }
    }

    private static class MyHandler extends Handler {
        private WeakReference<BookDetialActivity> mActivity;

        public MyHandler(BookDetialActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mActivity.get().loadCount++;
                    if (mActivity.get().loadCount == 2) {
                        mActivity.get().loadCount = 0;
                        MProgressDialog.dismissProgress();
                        Toast.makeText(mActivity.get(), "下载完成", Toast.LENGTH_SHORT).show();
                    //    mActivity.get().adapter.notifyItemChanged(mActivity.get().position);
                        ((TextView) mActivity.get().view).setText("已下载");
                        LocalUtils.SaveMete(mActivity.get().db, mActivity.get().resource, mActivity.get().metaName, mActivity.get().lrcName, mActivity.get().bookDetailResponse);
//                        mActivity.get().adapter.getData().clear();
//                        mActivity.get().adapter.replaceData(mActivity.get().newData);
                        MusicActivity.mp3Infos = LocalUtils.getList(mActivity.get().db, mActivity.get().bookDetailResponse.getId());
                        if (isServiceRunning(mActivity.get().getApplicationContext(), "com.zjeav.lingjiao.ui.music.MusicService")) {
                            mActivity.get().stopService(new Intent(mActivity.get().getApplicationContext(), MusicService.class));
                        } else {
                            SharedPreferencesUtils.setParam(mActivity.get().getApplicationContext(), "currentTime", 0);
                        }
                        for (int i = 0; i < MusicActivity.mp3Infos.size(); i++) {
                            if (MusicActivity.mp3Infos.get(i).getId() == mActivity.get().resource.getId()) {
                                Intent musicintent = new Intent(mActivity.get(), MusicActivity.class);
                                //当前播放的位置
                                musicintent.putExtra("position", String.valueOf(i));
                                musicintent.putExtra("type", 1);
                                //启动音乐播放界面
                                mActivity.get().startActivity(musicintent);
                            }
                        }
                    }
                    break;
            }
        }
    }


    @Override
    public void getLoadResult(ResponseBody body, int type) {
        if (type == 1) {
            downBody = body;
            new Thread(networkTask1).start();
        } else {
            downBody2 = body;
            new Thread(networkTask2).start();
        }

    }

    @Override
    public void getAccessToken(AccessToken token) {

    }

    @Override
    public void showError(Throwable throwable) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();

    }

    Runnable networkTask1 = new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 0;
            myHandler.sendMessage(message);
            FileUtils.writeResponseBodyToDisk(BookDetialActivity.this, downBody, metaName, myHandler);
        }
    };
    Runnable networkTask2 = new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 0;
            myHandler.sendMessage(message);
            FileUtils.writeResponseBodyToDisk(BookDetialActivity.this, downBody2, lrcName, myHandler);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }
}
